﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using BluePortal.Framework;
using System.Xml.Linq;
using System.Xml;
using System.Web.Security;
using BluePortal.Medias.Core;

namespace BluePortal.Medias.Services.Rss
{
    public class MediaRSS : IHttpHandler
    {        
        public void GenerateRss(HttpContext context, IEnumerable<Media> medias)
        {
            context.Response.ContentType = "text/xml";
            XNamespace media = "http://search.yahoo.com/mrss";
            List<Media> videos2xml = medias.ToList();

            XDocument rss = new XDocument(
                new XElement("rss", new XAttribute("version", "2.0"),
                    new XElement("channel",
                        new XElement("title", "Channel Medias BluePortal"),
                        new XElement("link", ""),
                        new XElement("description", ""),
                        new XElement("language", ""),
                        new XElement("pubDate", DateTime.Now.ToString("r")),
                        new XElement("generator", "XLinq"),

                        from v in videos2xml
                        select new XElement("item",
                                   new XElement("title", v.Title.Trim()),
                                   new XElement("link", "",
                                       new XAttribute("rel", "alternate"),
                                       new XAttribute("type", "text/html"),
                                       new XAttribute("href", String.Format("/Details.aspx?vid={0}", v.ID))),
                                   new XElement("id", NotNull(v.ID)),
                                   new XElement("pubDate", v.PublishDate.Value.ToLongDateString()),
                                   new XElement("description",
                                       new XCData(String.Format("<a href='/Details.aspx?vid={1}'> <img src='/Images/ThumbnailHandler.ashx?vid={1}' align='left' width='120' height='90' style='border: 2px solid #B9D3FE;'/></a><p>{0}</p>", v.Description, v.ID))),
                                   new XElement("author", NotNull(v.Owner)),                                       
                                   new XElement("link",
                                       new XAttribute("rel", "enclosure"), 
                                       new XAttribute("href", String.Format("/Details.aspx?vid={0}", v.ID)),                                        
                                        new XAttribute("type", "video/wmv")),
                                   new XElement(XName.Get("title", "http://search.yahoo.com/mrss"), v.Title.Trim()),
                                   new XElement(XName.Get("thumbnail", "http://search.yahoo.com/mrss"), "",
                                       new XAttribute("url", String.Format("/Images/ThumbnailHandler.ashx?vid={0}", v.ID)),
                                       new XAttribute("width", "320"),
                                       new XAttribute("height", "240")),
                                   new XElement(XName.Get("content", "http://search.yahoo.com/mrss"), "a",
                                        new XAttribute("url", String.Format("/Details.aspx?vid={0}", v.ID)),
                                        new XAttribute("fileSize", Default(v.FileSize)),
                                        new XAttribute("type", "video/wmv"),                                                                                
                                        new XAttribute("height", Default(v.Height)),
                                        new XAttribute("width", Default(v.Width))
                                        )
                                )
                         )
                    )
                   );

            using (XmlWriter writer = new XmlTextWriter(context.Response.OutputStream, Encoding.UTF8))
            {
                try
                {
                    rss.WriteTo(writer);
                }
                catch (Exception ex)
                {
                    Log.LogError("VideoRss", "GenerateRss", ex);
                }
            }

        }

        #region IHttpHandler Members

        public bool IsReusable
        {
            get { return true; }
        }

        public void ProcessRequest(HttpContext context)
        {
            BCMedia bc = new BCMedia();
            string guid = null;
            if ((guid = context.Request.QueryString.Get("chid")) != null)
            {
                //string ticket = null;
                //if ((ticket = context.Request.QueryString.Get("t")) != null)
                //{
                //    FormsAuthenticationTicket t = FormsAuthentication.Decrypt(ticket);
                GenerateRss(context, bc.FindByChannel(new Guid(guid), null));
                //}
            }
            else if ((guid = context.Request.QueryString.Get("category")) != null)
            {
                GenerateRss(context, bc.FindByCategory(new Guid(guid), null));
            }
            else if ((guid = context.Request.QueryString.Get("playlist")) != null)
            {
                GenerateRss(context, bc.FindByPlayList(new Guid(guid), null));
            }
            else if ((guid = context.Request.QueryString.Get("tag")) != null)
            {
                GenerateRss(context, bc.FindByTag(guid, null));
            }
            else
            {
                GenerateRss(context, bc.FindAll(null));
            }
        }

        #endregion

        public static object Default(Nullable<int> v)
        {
            return v.GetValueOrDefault();
        }

        public static object Default(Nullable<long> v)
        {
            return v.GetValueOrDefault();
        }

        public static object NotNull(object o)
        {
            if (o == null) return "";
            return o;
        }

    }
}
